package com.example.app.components.MyImage

import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.DefaultAlpha
import androidx.compose.ui.graphics.FilterQuality
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import coil.compose.AsyncImagePainter
import coil.compose.rememberAsyncImagePainter
import coil.decode.SvgDecoder
import coil.imageLoader
import coil.request.CachePolicy
import coil.request.ImageRequest
import com.example.app.network.api.ServiceConfig
import com.example.app.util.CacheUtil
import okhttp3.Headers

@Composable
fun MyAsyncSvgImage(
    path: String,
    contentDescription: String? = "",
    modifier: Modifier = Modifier.size(24.dp),
    alignment: Alignment = Alignment.Center,
    contentScale: ContentScale = ContentScale.Fit,
    alpha: Float = DefaultAlpha,
    colorFilter: ColorFilter? = null,
) {
    var remotePath =
        ServiceConfig.SERVER_URL + "file/resource/icon?action=showColorIcon&filename=" + path
    var context = LocalContext.current
    var imageLoader = context.imageLoader
    var cache = imageLoader.diskCache?.get(remotePath)
    val headers = Headers.Builder().add("token", CacheUtil.getToken()).build()
    var imageRequest = ImageRequest.Builder(LocalContext.current).data(remotePath).headers(headers)
        .networkCachePolicy(if (cache != null) CachePolicy.DISABLED else CachePolicy.ENABLED)
        .networkCachePolicy(CachePolicy.ENABLED).memoryCachePolicy(CachePolicy.ENABLED)
        .decoderFactory(SvgDecoder.Factory()).diskCachePolicy(CachePolicy.ENABLED)
        .diskCacheKey(remotePath).build()
    var painter = rememberAsyncImagePainter(model = imageRequest,
                                            onSuccess = {},
                                            onError = {
                                                      println("it----->${it}")
                                            },
                                            onLoading = {})


    MyImage(
        painter = painter, contentDescription, modifier, alignment, contentScale, alpha, colorFilter
    )
}